package com.djj.nanny.service.impl;

import com.aliyun.oss.OSSClient;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import com.djj.nanny.common.Result;
import com.djj.nanny.enumClass.FileType;
import com.djj.nanny.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URI;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;


@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final static Logger LOGGER = LoggerFactory.getLogger(FileServiceImpl.class);

    @Resource
    private OSSClient ossClient;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @SneakyThrows
    @Override
    public Result<?> loadFile(MultipartFile file, FileType fileType) {
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();

        String pathDir = fileType.getTypeName() + "/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        fileName = pathDir + "/" + UUID.randomUUID() + Objects.requireNonNull(fileName).substring(fileName.lastIndexOf("."));

        ossClient.putObject(bucket, fileName, inputStream);
        LOGGER.info("upload FILE:{}", file.getOriginalFilename());

        String url = "https://" + bucket + "." + endpoint + "/" + fileName;
        return Result.success(url);
    }

    @SneakyThrows
    @Override
    public Result<?> deleteFile(String url) {
        url = new URI(url).getPath().substring(1);
        ossClient.deleteObject(bucket, url);
        LOGGER.info("delete FILE:{}", url);
        return Result.success();
    }

    @SneakyThrows
    @Override
    public List<String> uploadMultiple(List<MultipartFile> files) {
        List<String> urlList = new ArrayList<>();

        files.forEach(file -> {
            try {
                Result<?> result = loadFile(file, FileType.IMG);
                urlList.add(result.getData().toString());
            } catch (Exception e) {
                LOGGER.error("文件上传失败！", e);
                urlList.forEach(this::deleteFile);
                throw new RuntimeException(e);
            }
        });

        return urlList;
    }
}
